﻿using System;
using System.Linq;
using System.Linq.Dynamic;
using System.Web.Mvc;
using ChoViet.CMS.ViewModels;
using ChoViet.Lib.Common;
using ChoViet.Lib.Helpers;
using ChoViet.Lib.Paging;
using ChoViet.Model;
namespace ChoViet.CMS.Controllers
{
    [RoleHelper(Roles = RoleSystem.Dictionary)]
    public class EventController : BaseController
    {
        /// <summary>
        /// Created by: VietLv
        /// Created date: 28/06/2013
        /// Description: Manage Event
        /// </summary>

        ChoVietDataContext eDataContext = new ChoVietDataContext();

        #region GET/Index
        public ActionResult IndexCms(int? page)
        {
            try
            {
                if (!page.HasValue) page = 1;
                string order = UserState.getUserStateFromRequest("Tag.order", "order", "ID").ToString();
                string orderDir = UserState.getUserStateFromRequest("Tag.orderDir", "orderDir", "desc").ToString();
                string keyword = UserState.getUserStateFromRequest("Tag.Keyword", "Keyword", "").ToString();
                int pageSize = int.Parse(UserState.getUserStateFromRequest("Tags.pageSize", "PageSize", 20).ToString());
                var listEvent = eDataContext.Events
                                .Where(t => (string.IsNullOrEmpty(keyword) ? true :
                                (t.Title.ToString().ToLower().Contains(keyword.ToLower().Trim())
                                )))
                                .OrderBy(string.Format("{0} {1}", order, orderDir))
                                .ToPagedList(page.Value - 1, pageSize);

                ViewData["orderDir"] = orderDir;
                ViewData["order"] = order;
                return View(new IndexEventViewModel
                {
                    Events = listEvent,
                    Keyword = keyword
                });
            }
            catch (Exception ex)
            {
                ViewData["MessageInfo"] = ex.Message;
                return View();
            }
        }
        #endregion

        #region POST: /Event/CreateCms
        public ActionResult CreateCms()
        {
            try
            {
                return View();
            }
            catch (Exception ex)
            {
                return View();
            }
        }
        #endregion

        #region POST: /Event/CreateCms
        [HttpPost]
        public ActionResult CreateCms(Event ev)
        {
            try
            {
                UpdateModel(ev);
                ev.AddBy = UserManager.GetUserId();
                ev.AddDate = DateTime.Now;
                eDataContext.Events.InsertOnSubmit(ev);
                eDataContext.SubmitChanges();
                Messages.ClearAllMessage();
                Messages.AddFlashMessage("Thêm chuyên mục mới thành công");
                return RedirectToAction("IndexCms");
            }
            catch (Exception ex)
            {
                Messages.ClearAllMessage();
                Messages.AddErrorFlashMessage("Thêm chuyên mục mới không thành công. Vui lòng thử lại với dữ liệu khác");
                return View();
            }
        }
        #endregion

        #region GET: /Event/EditCms
        public ActionResult EditCms(int id)
        {
            try
            {
                var currentEvent = eDataContext.Events.Where(e => e.ID == id).SingleOrDefault();
                return View(currentEvent);
            }
            catch (Exception ex)
            {
                ViewData["MessageInfo"] = "Không tìm thấy tag hiện tại. Vui lòng thử lại với dữ liệu khác";
                return View();
            }
        }
        #endregion

        #region POST: /Event/EditCms
        [HttpPost]
        public ActionResult EditCms(int id, Event ev)
        {
            try
            {
                if (id < 0) throw new NotSupportedException();

                var currentEvent = eDataContext.Events.Where(e => e.ID == id).SingleOrDefault();
                UpdateModel(currentEvent);
                eDataContext.SubmitChanges();
                Messages.AddFlashMessage("Sửa chủ đề - sự kiện thành công");
                return RedirectToAction("IndexCms");
            }
            catch (Exception ex)
            {
                Messages.AddFlashMessage("Sửa chủ đề - sự kiện không thành công");
                return View();
            }
        }
        #endregion

        #region GET: /Event/Delete
        public ActionResult DeleteCms(int id)
        {
            try
            {

                var currentEvent = eDataContext.Events.Where(e => e.ID == id).SingleOrDefault();
                return View(currentEvent);
            }
            catch (Exception ex)
            {
                ViewData["MessageInfo"] = "Có lỗi xảy ra bạn không thể xóa được";
                return View();
            }
        }
        #endregion

        #region POST: /Event/Delete
        [HttpPost]
        public ActionResult DeleteCms(int id, FormCollection frm)
        {
            try
            {
                var currentEvent = eDataContext.Events.Where(ca => ca.ID == id).SingleOrDefault();
                if (currentEvent != null)
                {
                    // Delete all article before delete current event
                    var articles = eDataContext.Articles.Where(e => e.EventID == id).ToList();
                    if (articles.Count() > 0)
                    {
                        eDataContext.Articles.DeleteAllOnSubmit(articles);
                        eDataContext.SubmitChanges();
                    }
                }
                eDataContext.Events.DeleteOnSubmit(currentEvent);
                eDataContext.SubmitChanges();
                return RedirectToAction("IndexCms");
            }
            catch (Exception ex)
            {
                ViewData["MessageInfo"] = "Có lỗi xảy ra bạn không thể xóa được";
                return View();
            }
        }
        #endregion

        #region GET: /Event/Detail
        public ActionResult DetailCms(int id)
        {
            try
            {
                var currentEvent= eDataContext.Events.Where(ca => ca.ID == id).SingleOrDefault();

                return View(currentEvent);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        #endregion

    }
}
